import time
from airtest.core.api import connect_device, swipe, snapshot
from poco.drivers.ios import iosPoco
import subprocess

# 启动抖音应用
def start_douyin():
    try:
        result = subprocess.run(["tidevice", "launch", "com.ss.iphone.ugc.Aweme"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode == 0:
            print("抖音启动成功")
        else:
            print("抖音启动失败:", result.stderr.decode())
    except Exception as e:
        print(f"启动抖音时发生错误: {e}")

# 退出抖音应用
def stop_douyin():
    try:
        result = subprocess.run(["tidevice", "kill", "com.ss.iphone.ugc.Aweme"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        if result.returncode == 0:
            print("抖音退出成功")
        else:
            print("抖音退出失败:", result.stderr.decode())
    except Exception as e:
        print(f"退出抖音时发生错误: {e}")

# 封装滑动操作
def swipe_up():
    try:
        swipe((0.5, 0.8), (0.5, 0.2))
        print("滑动成功")
    except Exception as e:
        print(f"滑动操作失败: {e}")

def main():
    try:
        # 连接到设备
        connect_device("iOS:///127.0.0.1:8100")

        # 启动抖音应用
        start_douyin()

        # 初始化 Poco
        poco = iosPoco()

        # 等待40秒确保应用启动和加载页面
        print("等待40秒...")
        time.sleep(40)

        # 确保应用已启动并可滑动
        for i in range(2):
            print(f"第 {i+1} 次滑动")
            swipe_up()
            time.sleep(10)  # 每次滑动中间等待10秒

        # 截图保存为证据
        snapshot(filename="douyin_screenshot.png")
        print("截图已保存")

    except Exception as e:
        print(f"执行过程中发生错误: {e}")

    finally:
        # 退出应用
        stop_douyin()

if __name__ == "__main__":
    main()